<script setup lang="ts">
defineOptions({
  name: "createReplaceFFU"
});
import { PxMessage } from "px-ui";
import { getAllFFU, getFFUDetail, queryChildByTypeCodeAndItemValue, getTeamList, getGroupList } from "@/api/machineClass";
import { onMounted, reactive, ref, toRefs, nextTick, watch } from "vue";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";

const accessToken = getToken().accessToken || "";

const url = ref<string>(`${import.meta.env.VITE_API_URL_PMS_NEW}/#/pmPlan/list?ssoToken=${accessToken}&isHiddenMenu=true`);

const data = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  formData: {
    creatorName: "",
    creatorId: "",
    className: "MACHINE",
    excutePerson: "",
    planName: "FFU化滤测试保养工单0909",
    eqpGroupId: "1823245006090670080",
    planNote: "需要更换哪些滤材",
    ruleCode: "CTMACHINE202408200001",
    eqpParts: { ffu组名: "[化滤类型=规格, 3号过滤器=VOC888]", "Group1-16:G9F16": "[5号过滤器=JX1243]" },
    estTime: null,
    outboundReq: "",
    teamId: "",
    earlyTime: 1,
    lateTime: 1,
    // facCode: "FAC_83abf9",
    systemCode: ""
  },
  filterTypeList: [],
  filterModelLsit: [
    {
      name: "碱性滤膜",
      value: "JX1243"
    },
    {
      name: "碱性滤膜2类",
      value: "JXLM000"
    }
  ],
  componeyList: [
    {
      name: "美埃",
      value: "1"
    }
  ],
  filterList: [],
  dateRange: [],
  peopleList: [],
  rules: {
    // creatorName: [{ required: true, message: "工单创建人不能为空", trigger: "blur" }],
    teamId: [{ required: true, message: "工单执行人不能为空", trigger: "blur" }]
  },
  tableTotalList: [],
  ffuList: [],
  tableList: [],
  // 编辑的表格行
  tableRowEditIndex: undefined,
  // 编辑的表格列
  tableColumnEditIndex: undefined,
  total: 0
});

const {
  queryParams,
  rules,
  total,
  tableTotalList,
  tableList,
  ffuList,
  peopleList,
  formData,
  dateRange,
  filterTypeList,
  filterList,
  filterModelLsit,
  componeyList
} = toRefs(data);
const ticketType = ref("手动");
const ticketTypeList = ref([
  {
    id: 1,
    itemName: "手动"
  }
]);

const showTable = ref(true);
const areaList = ref([
  {
    value: "CMP",
    label: "CMP"
  },
  {
    value: "LITHO",
    label: "LITHO"
  },
  {
    value: "IMP",
    label: "IMP"
  },
  {
    value: "ETCH",
    label: "ETCH"
  },
  {
    value: "WET",
    label: "WET"
  }
]);
const replaceTypeList = ref([
  {
    value: "1",
    label: "失效更换"
  },
  {
    value: "2",
    label: "更换配置"
  }
]);

const popup_width = ref<string>("968px");
const popup_height = ref<string>("480px");

const router = useRouter();

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const loading = ref(false);

const getHour = (s1, s2) => {
  let reDate = /\d{4}-\d{1,2}-\d{1,2} /;
  s1 = new Date((reDate.test(s1) ? s1 : "2018-1-1 " + s1).replace(/-/g, "/"));
  s2 = new Date((reDate.test(s2) ? s2 : "2018-1-1 " + s2).replace(/-/g, "/"));
  let ms = s2.getTime() - s1.getTime();
  if (ms < 0) return 0;
  return Math.floor(ms / 1000 / 60 / 60); //小时
};

// 合并同类项数组
const mergeDataByProperty = arr => {
  const merged = [];
  let propertyValues = {};
  const keyArr: any = Array.from(new Set(arr.map(item => item.ffuCode))) || [];
  for (const val in keyArr) {
    propertyValues[keyArr[val]] = [];
    console.log(val);
    arr.forEach(item => {
      if (item.ffuCode === keyArr[val]) {
        propertyValues[keyArr[val]].push(`${item.filterCode}=${item.filterModel}`);
      }
    });
  }
  return propertyValues;
};

const commitFn = () => {
  // if (dateRange.value.length < 1) {
  //   PxMessage({
  //     type: "warning",
  //     message: "请输入计划执行时间"
  //   });
  //   return;
  // }
  // const param = { ...formData.value };
  // param.estTime = getHour(dateRange.value[0], dateRange.value[1]);
  // const arr = [];
  // tableList.value.forEach(item => {
  //   if (item.switchType) {
  //     arr.push(item);
  //   }
  // });
  // console.log(tableList.value, arr, mergeDataByProperty(arr), "888888888888");
  // param.eqpParts = mergeDataByProperty(arr);
  // console.log(tableList.value);
  // console.log("保存。。。。", param);
  // getFFUDetail(param).then(res => {
  //   if (res) {
  //     PxMessage({
  //       type: "success",
  //       message: "操作成功"
  //     });
  //   }
  // });
  url.value = `${import.meta.env.VITE_API_URL_PMS_NEW}/#/pmPlan/list?pmType=UNS&isAdd=true&ssoToken=${accessToken}&isHiddenMenu=true&eqpId=${formData.value.eqpGroupId}&ruleCode=${formData.value.ruleCode}&isClose=true`;
  // router.push({
  //   path: "/all/equip/epm/plan/list",
  //   query: {
  //     fullpath: `/pmPlan/list?pmType=UNS&isAdd=true&ssoToken=${accessToken}&isHiddenMenu=true&eqpId=${formData.value.eqpGroupId}&ruleCode=${formData.value.ruleCode}`
  //   }
  // });
  showTable.value = false;
};

const samplePersonIdChange = (val: any) => {
  // formData.dosingPerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};

const handleChangeReplace = row => {
  if (row.replaceType === "1") {
    row.filterDisabled = true;
  } else {
    row.filterDisabled = false;
  }
};

const handleChangeFilter = row => {
  const selected = filterTypeList.value.filter(item => item.itemName === row.filterType);
  // filterModelLsit.value = [
  //   {
  //     name: "碱性滤膜",
  //     value: "JX1243"
  //   },
  //   {
  //     name: "碱性滤膜2类",
  //     value: "JXLM000"
  //   }
  // ];
};

watch(
  () => tableList.value,
  newVal => {
    spanPropGroup(newVal); // 合并行
  }
);
// 定义表格列
interface TableColumn {
  label: string;
  width: string;
}

//需要判断的属性组
const spanProps = ["area", "filterInstallDate", "ffuName"];

let rowSpansMap = new Map(); //存需要开始合并的行号，向下合并多少行

/**
 * 根据列表数据得出需要合并的行
 * @param data 列表数据
 */
const spanPropGroup = (data: any) => {
  let oldRow: any = null; //需要合并的行
  rowSpansMap = new Map(); //重置Map

  oldRow = data[0]; //默认第0行为需要合并的行
  rowSpansMap.set(0, 1); //第0行，向下合并一行(其实就是自己单独一行)
  let spanRow = 0; //记录需要开始合并的行号
  for (let i = 1; i < data.length; i++) {
    const item = data[i];
    let isSame = true;
    //遍历需要判断的属性判断对应值是否全部相等
    for (let j = 0; j < spanProps.length; j++) {
      const prop = spanProps[j];
      //只要有一个属性值不相等则记录新的需要合并的行号
      if (item[prop] != oldRow[prop]) {
        oldRow = item;
        rowSpansMap.set(i, 1);
        spanRow = i;
        isSame = false;
        break;
      }
    }
    //如果所有属性值相同则所需要合并的行数+1
    if (isSame) {
      let span = rowSpansMap.get(spanRow);
      rowSpansMap.set(spanRow, span + 1);
    }
  }
};

const objectSpanMethod: any = ({ row, column, rowIndex, columnIndex }) => {
  //采样值1-5列所对应的行不需要合并
  if (columnIndex == 0 || columnIndex == 1 || columnIndex == 2) {
    //根据当前行号从map中获取开始合并的行根据当前行号从map中获取开始合并的行号，向下合并多少行
    const span = rowSpansMap.get(rowIndex);
    if (span != null) {
      return {
        rowspan: span, //向下合并span行
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};

const getAllFilters = async id => {
  const params = {
    group: id || "group3"
  };
  const data: any = await getAllFFU(params);
  const arr = [];
  data?.ffuList.forEach(item => {
    item.filters.map(el => {
      Object.keys(item).forEach(e => {
        el[e] = item[e];
      });
      el.replaceType = "2";
      el.switchType = true;
      el.filterDisabled = false;
      el.filterModel = null;
      el.componeyName = "美埃";
      el.num = 1;
      arr.push(el);
    });
  });
  ffuList.value = data.ffuList;
  tableList.value = arr || [];
};
onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const paramValue = urlParams.get("id");
  console.log("paramValue", paramValue);
  getAllFilters(paramValue);
  const data: any = await getTeamList({
    className: "MACHINE"
  });
  // peopleList.value = await getGroupList({ className: "MACHINE" });
  peopleList.value = data;
  // 化滤类型
  queryChildByTypeCodeAndItemValue({
    value: "FFUHLLX",
    typeCode: "MCTS"
  }).then((res: any) => {
    filterTypeList.value = res ? res : [];
  });

  const resData: any = await queryChildByTypeCodeAndItemValue({
    value: "EQP_CONSUMABLE",
    typeCode: "CONSUMABLE_LIFE_CYCLE"
  });
  formData.value.ruleCode = JSON.parse(resData.filter(el => el.itemValue === "EQP_FFU")[0].itemDesc).RULE_CODE;
  formData.value.eqpGroupId = JSON.parse(resData.filter(el => el.itemValue === "EQP_FFU")[0].itemDesc).EQP_TYPE_ID;
  // 检测机构
  // queryChildByTypeCodeAndItemValue({
  //   value: "DU01",
  //   typeCode: "MCTS"
  // }).then((res: any) => {
  //   organizationArr.value = res ? res : [];
  // });
  // 取样点
  // queryChildByTypeCodeAndItemValue({
  //   value: "CSP01",
  //   typeCode: "MCTS"
  // }).then((res: any) => {
  //   locationArr.value = res ? res : [];
  // });
});
</script>

<template>
  <div style="width: 100%; height: 100%; min-height: 800px">
    <div v-if="showTable" class="topology-common-popup-base">
      <div class="common-popup-content-content">
        <px-form ref="detailruleFormRef" :rules="rules" :model="formData" label-width="110px">
          <div class="form-div">
            <px-row>
              <px-col :span="12">
                <px-form-item label="工单类型">
                  <px-select v-model="ticketType" placeholder="请选择工单类型" style="width: 100%" filterable disabled clearable>
                    <px-option v-for="dict in ticketTypeList" :key="dict.id" :label="dict.itemName" :value="dict.itemName" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="工单创建人" prop="creatorName">
                  <px-input v-model="formData.creatorName" placeholder="工单创建人" /> </px-form-item
              ></px-col>
            </px-row>
            <px-row>
              <px-col :span="12">
                <!-- <px-form-item label="工单执行人" prop="teamId">
                <px-select v-model="formData.teamId" filterable clearable placeholder="请选择工单执行人" style="width: 100%">
                  <px-option v-for="item in peopleList" :key="item.userId" :label="item.username" :value="item.userId" />
                </px-select>
              </px-form-item> -->
                <px-form-item label="工单执行人" prop="teamId">
                  <px-select v-model="formData.teamId" filterable clearable style="width: 100%" placeholder="请选择" @change="samplePersonIdChange">
                    <px-option v-for="item in peopleList" :key="item.id" :label="item.name" :value="item.id" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="计划执行时间" style="width: 100%">
                  <px-date-picker
                    v-model="dateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :default-time="defaultTime"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </px-form>
        <px-table
          v-loading="loading"
          :header-cell-style="{ background: '#e7eefb', color: '#000' }"
          max-height="280"
          border
          :data="tableTotalList"
          show-overflow-tooltip
        >
          <px-table-column label="本工单FFU总数" prop="id" width="180" />
          <px-table-column label="本工单化滤总数" prop="ffuCode" width="180" />
          <px-table-column label="酸性" prop="ffuCode" />
          <px-table-column label="碱性" prop="ffuCode" />
          <px-table-column label="RC" prop="ffuGroup" />
          <px-table-column label="Diffusion">
            <px-table-column label="酸性" prop="ffuCode" />
            <px-table-column label="碱性" prop="ffuCode" />
            <px-table-column label="RC" prop="ffuGroup" />
          </px-table-column>
          <px-table-column label="CMP">
            <px-table-column label="酸性" prop="ffuCode" />
            <px-table-column label="碱性" prop="ffuCode" />
            <px-table-column label="RC" prop="ffuGroup" />
          </px-table-column>
        </px-table>
        <barTitle title="化滤列表" style="margin: 16px 0" />
        <!-- :span-method="objectSpanMethod" -->
        <px-table
          v-loading="loading"
          :header-cell-style="{ background: '#e7eefb', color: '#000' }"
          max-height="420"
          border
          :data="tableList"
          :span-method="objectSpanMethod"
          show-overflow-tooltip
        >
          <px-table-column label="区域" prop="area" width="80" fixed />
          <px-table-column label="上次更换日期" prop="filterInstallDate" width="120" fixed />
          <px-table-column label="FFU" prop="ffuName" width="120" fixed />
          <px-table-column label="化滤编号" prop="filterCode" width="120" fixed />
          <px-table-column label="类型" prop="filterType" />
          <px-table-column label="分组" prop="ffuGroup" />
          <px-table-column label="更换周期(天)" prop="lifecycle_exp" width="100" />
          <px-table-column label="化滤安装日期" prop="filterInstallDate" width="120" />
          <px-table-column label="已运行天数" prop="lifecycle_act" width="100" />
          <px-table-column label="化滤剩余寿命" prop="lifecycle_exp_left" width="120" />
          <px-table-column label="单片/双片" prop="ffuId" width="100" />
          <!-- <px-table-column label="化滤编号" prop="filterCode" width="200">
            <template #default="scope">
              <px-input
                v-if="data.tableRowEditIndex === scope.$index && data.tableColumnEditIndex == scope.column.id"
                ref="tableRowInputRef"
                v-model="scope.row.filterCode"
                @keyup.enter="
                  $event => {
                    $event.target.blur();
                  }
                "
                @blur="onInputTableBlur(scope, scope.row.filterCode)"
              />
              <p v-else class="eidt-row-p">
                {{ scope.row.filterCode }}<px-icon style="margin-left: 5px; cursor: pointer" @click="dbClickCell(scope)"><EditPen /></px-icon>
              </p>
            </template>
          </px-table-column> -->
          <px-table-column label="更换类型" width="170">
            <template #default="scope">
              <px-select v-model="scope.row.replaceType" filterable placeholder="请选择更换类型" @change="handleChangeReplace(scope.row)">
                <px-option v-for="item in replaceTypeList" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </template>
          </px-table-column>
          <px-table-column label="化滤类型" prop="filterType" width="170">
            <template #default="scope">
              <px-select
                v-model="scope.row.filterType"
                placeholder="请选择化滤类型"
                filterable
                :disabled="scope.row.filterDisabled"
                @change="handleChangeFilter(scope.row)"
              >
                <px-option v-for="item in filterTypeList" :key="item.id" :label="item.itemName" :value="item.itemName" />
              </px-select>
            </template>
          </px-table-column>
          <px-table-column label="规格型号" width="170">
            <template #default="scope">
              <px-select v-model="scope.row.filterModel" filterable placeholder="请选择规格型号">
                <px-option v-for="item in filterModelLsit" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </template>
          </px-table-column>
          <px-table-column label="厂家" width="170">
            <template #default="scope">
              <px-select v-model="scope.row.componeyName" filterable placeholder="请选择厂家">
                <px-option v-for="item in componeyList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </template>
          </px-table-column>
          <px-table-column label="申请数量" prop="num" width="180">
            <template #default="scope">
              <px-input-number v-model="scope.row.num" :min="1" :max="1000000" :value-on-clear="1" step-strictly />
            </template>
          </px-table-column>
          <px-table-column label="生效" width="70" fixed="right">
            <template #default="scope">
              <px-switch v-model="scope.row.switchType" />
            </template>
          </px-table-column>
          <template #empty>
            <px-empty :image-size="150" />
          </template>
        </px-table>
        <div class="px-dialog-footer">
          <!-- <px-button>取消</px-button> -->
          <px-button type="primary" @click="commitFn">保存</px-button>
        </div>
      </div>
    </div>
    <div v-if="!showTable" style="width: 100%; height: 100%; min-height: 800px">
      <iframe :src="url" width="100%" height="100%" frameborder="0" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.topology-common-popup-base {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;

  .common-popup-content-content {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    width: v-bind(popup_width);
    height: v-bind(popup_height);
    padding: 16px;
    background-color: white;

    .px-dialog-footer {
      position: absolute;
      bottom: 0;
      left: 0;
      z-index: 2002;
      width: 100%;
      height: 50px;
      padding-top: 10px;
      padding-right: 34px;
      text-align: right;
      background: white;
      box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
    }

    .content-title {
      width: 100%;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      letter-spacing: 2px;
    }
  }
}
</style>
